import {
	showInfo
} from "../utils/ToastUtils";
import LogService from "./LogService";

class BleDeviceService {

	/**
	 * 打开蓝牙
	 * @returns {Promise<unknown>}
	 */
	openBlu() {
		let promise = new Promise(function(resolve, reject) {
			uni.openBluetoothAdapter({
				success: function(res) {
					LogService.debug("openBluetoothAdapter success", res)
					resolve(true);
				},
				fail: function(res) {
					LogService.error("openBluetoothAdapter fail", res);
					// showInfo("请打开蓝牙");
					resolve(false);
				}
			})
		});
		return promise;
	}

	/**
	 * 扫描设备
	 * @returns {Promise<void>}
	 */
	async scan() {
		const that = this;
		console.log("进入scan");
		if (!await this.isAvaible()) {
			console.log("扫描返回蓝牙适配器不可用");
			return false;
		}
		console.log("start scan 扫描设备开始");
		// 以微信硬件平台的蓝牙智能灯为例，主服务的 UUID 是 FEE7。传入这个参数，只搜索主服务 UUID 为 FEE7 的设备
		uni.startBluetoothDevicesDiscovery({
			allowDuplicatesKey:true,
			success: function(res1) {
				LogService.info("startBluetoothDevicesDiscovery success", res1)
			},
			fail: function(err){
				LogService.info("startBluetoothDevicesDiscovery fail", err)
			}
		})
		return true;
	}

	onBluetoothDeviceFound(names,callback) {
		uni.onBluetoothDeviceFound((res) => {
			// console.log('has founded',res.devices);
			const devices = res.devices;
			if (!devices || devices.length < 1) {
				return;
			}
			for (let i = 0; i < names.length; i++) {
				for (const device of devices) {
					if((device.localName && device.localName.startsWith(names[i])) || (device.name && device.name.startsWith(names[i]))){
						console.log('new device list has founded',devices);
						!!callback && callback(devices);
					}
				}
			}
		})
	}

	/**
	 * RSSI: -83
	 advertisData: ArrayBuffer(9)
	 [[Int8Array]]: Int8Array(9) [76, 0, 16, 5, 69, 28, 123, 32, -23]
	 [[Uint8Array]]: Uint8Array(9) [76, 0, 16, 5, 69, 28, 123, 32, 233]
	 advertisServiceUUIDs: []
	 connectable: true
	 deviceId: "60:DE:8A:DC:3A:31"
	 localName: "alibaba-inc"
	 name: "alibaba-inc"
	 */
	getBluetoothDevices(names, callback,flag = true) {
		uni.getBluetoothDevices({
			success: function(res) {
				var devices = res.devices;
				if (!devices || devices.size == 0)
					return;
				if(flag){
					if (!!names)
						devices = devices.filter(value => {
							for (let i = 0; i < names.length; i++) {
								if (value.localName.startsWith(names[i]) || value.name.startsWith(names[i])) {
									return true;
								}
							}
							return false;
						});
				}
				!!callback && callback(devices);
				// devices.forEach(device => {
				//   LogService.info(name, device, ab2hex(device.advertisData))
				// })
			}
		})
	}

	async stopSCan() {
		console.log("进入停止扫描");
		if (!await this.isAvaible()) {
			// showInfo("请打开蓝牙");
			console.log("停止扫描显示适配器不可用");
			return;
		}
		console.log("停止扫描显示适配器可用");
		try{
			const res = await uni.stopBluetoothDevicesDiscovery();
			console.log("stopBluetoothDevicesDiscovery", res);
		}catch (e){
			console.log("stopBluetoothDevicesDiscovery error", e);
		}
	}

	async isAvaible() {
		try {
			console.log("检测蓝牙是否可用");
			const res = await this.getBluState();
			console.log("检测蓝牙 返回结果",res);
			const {
				available
			} = res;
			console.log("检测蓝牙 返回结果 available",available);
			return available;
		} catch (e) {
			return false;
		}
	}

	async isDiscovering() {
		try {
			const res = await this.getBluState();
			const {
				discovering
			} = res;
			return discovering ? 1 : 0;
		} catch (e) {
			return -1;
		}
	}

	/**
	 * available  boolean  蓝牙适配器是否可用
	 discovering  boolean  是否正在搜索设备
	 errMsg  string  成功：ok，错误：详细信息
	 */
	getBluState() {
		let promise = new Promise(function(resolve, reject) {
			uni.getBluetoothAdapterState({
				success: function(res) {
					LogService.info("getBluetoothAdapterState success", res);
					resolve(res);
				},
				fail: function(res) {
					LogService.info("getBluetoothAdapterState fail", res);
					reject(res);
				},
			})
		});
		return promise;
	}

}

export default new BleDeviceService();
